<template>
  <div class="loan-approval">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>放款审批</h3>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="贷款编号">
          <el-input v-model="searchForm.loanNo" placeholder="请输入贷款编号" />
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="审批状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="待审批" value="pending" />
            <el-option label="审批中" value="processing" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 审批列表 -->
      <el-table :data="approvalList" style="width: 100%" v-loading="loading">
        <el-table-column prop="loanNo" label="贷款编号" width="180" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="loanAmount" label="贷款金额" width="150">
          <template #default="scope">
            {{ formatAmount(scope.row.loanAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="loanTerm" label="贷款期限" width="120">
          <template #default="scope">
            {{ scope.row.loanTerm }}个月
          </template>
        </el-table-column>
        <el-table-column prop="purpose" label="贷款用途" width="150" />
        <el-table-column prop="status" label="审批状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentNode" label="当前节点" width="120" />
        <el-table-column prop="submitTime" label="提交时间" width="180" />
        <el-table-column label="操作" fixed="right" width="150">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleApproval(scope.row)"
              v-if="scope.row.status === 'pending'"
            >
              审批
            </el-button>
            <el-button
              link
              type="primary"
              @click="viewDetail(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="approvalDialogVisible"
      title="放款审批"
      width="60%"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="approvalFormRef"
        :model="approvalForm"
        :rules="approvalRules"
        label-width="120px"
      >
        <!-- 基本信息展示 -->
        <el-descriptions title="贷款基本信息" :column="2" border>
          <el-descriptions-item label="贷款编号">{{ currentLoan.loanNo }}</el-descriptions-item>
          <el-descriptions-item label="客户姓名">{{ currentLoan.customerName }}</el-descriptions-item>
          <el-descriptions-item label="贷款金额">{{ formatAmount(currentLoan.loanAmount) }}</el-descriptions-item>
          <el-descriptions-item label="贷款期限">{{ currentLoan.loanTerm }}个月</el-descriptions-item>
          <el-descriptions-item label="贷款用途">{{ currentLoan.purpose }}</el-descriptions-item>
          <el-descriptions-item label="担保方式">{{ currentLoan.guaranteeType }}</el-descriptions-item>
        </el-descriptions>

        <!-- 审批意见 -->
        <el-form-item label="审批决定" prop="decision" style="margin-top: 20px">
          <el-radio-group v-model="approvalForm.decision">
            <el-radio label="approve">通过</el-radio>
            <el-radio label="reject">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="审批意见" prop="comment">
          <el-input
            v-model="approvalForm.comment"
            type="textarea"
            rows="4"
            placeholder="请输入审批意见"
          />
        </el-form-item>

        <el-form-item label="放款金额" prop="approvedAmount" v-if="approvalForm.decision === 'approve'">
          <el-input-number
            v-model="approvalForm.approvedAmount"
            :min="0"
            :max="currentLoan.loanAmount"
            :step="1000"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="放款日期" prop="loanDate" v-if="approvalForm.decision === 'approve'">
          <el-date-picker
            v-model="approvalForm.loanDate"
            type="date"
            placeholder="选择放款日期"
            style="width: 200px"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="approvalDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitApproval(approvalFormRef)">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="审批详情"
      width="70%"
    >
      <el-descriptions title="贷款信息" :column="2" border>
        <el-descriptions-item label="贷款编号">{{ currentLoan.loanNo }}</el-descriptions-item>
        <el-descriptions-item label="客户姓名">{{ currentLoan.customerName }}</el-descriptions-item>
        <el-descriptions-item label="贷款金额">{{ formatAmount(currentLoan.loanAmount) }}</el-descriptions-item>
        <el-descriptions-item label="审批状态">
          <el-tag :type="getStatusType(currentLoan.status)">
            {{ getStatusText(currentLoan.status) }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 审批流程 -->
      <el-timeline style="margin-top: 20px">
        <el-timeline-item
          v-for="(activity, index) in approvalHistoryList"
          :key="index"
          :type="activity.type"
          :color="activity.color"
          :timestamp="activity.timestamp"
        >
          {{ activity.content }}
          <p v-if="activity.comment" style="color: #666; margin: 5px 0">
            审批意见：{{ activity.comment }}
          </p>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { lendingApi } from '@/api/lending'

export default {
  name: 'LendingApproval',
  setup() {
    // 搜索表单
    const searchForm = reactive({
      loanNo: '',
      customerName: '',
      status: ''
    })

    // 状态管理
    const loading = ref(false)
    const approvalList = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const approvalDialogVisible = ref(false)
    const currentLoan = ref({})
    const detailDialogVisible = ref(false)
    const approvalHistoryList = ref([])

    // 审批表单相关
    const approvalFormRef = ref(null)
    const approvalForm = reactive({
      decision: 'approve',
      comment: '',
      approvedAmount: 0,
      loanDate: new Date()
    })

    // 表单验证规则
    const approvalRules = {
      decision: [
        { required: true, message: '请选择审批决定', trigger: 'change' }
      ],
      comment: [
        { required: true, message: '请输入审批意见', trigger: 'blur' }
      ],
      approvedAmount: [
        { required: true, message: '请输入批准金额', trigger: 'blur' }
      ]
    }

    // 获取待审批列表
    const getPendingApprovalList = async () => {
      try {
        loading.value = true
        const params = {
          loanNo: searchForm.loanNo,
          customerName: searchForm.customerName,
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }
        
        if (searchForm.status) {
          params.status = searchForm.status
        }
        
        const res = await lendingApi.getPendingApprovalList(params)
        approvalList.value = res.data.list
        total.value = res.data.total
      } catch (error) {
        console.error('获取审批列表失败', error)
        ElMessage.error('获取审批列表失败')
      } finally {
        loading.value = false
      }
    }

    // 查看详情
    const viewDetail = async (row) => {
      try {
        loading.value = true
        const detailRes = await lendingApi.getDetail(row.disbursementId)
        currentLoan.value = detailRes.data
        
        // 获取审批历史
        const historyRes = await lendingApi.getApprovalHistory(row.disbursementId)
        approvalHistoryList.value = historyRes.data
        
        detailDialogVisible.value = true
      } catch (error) {
        console.error('获取详情失败', error)
        ElMessage.error('获取详情失败')
      } finally {
        loading.value = false
      }
    }

    // 处理审批
    const handleApproval = async (row) => {
      currentLoan.value = row
      approvalForm.decision = 'approve'
      approvalForm.comment = ''
      approvalForm.approvedAmount = row.loanAmount || 0
      approvalForm.loanDate = new Date()
      approvalDialogVisible.value = true
    }

    // 提交审批
    const submitApproval = async (formEl) => {
      if (!formEl) return
      
      await formEl.validate(async (valid) => {
        if (valid) {
          try {
            loading.value = true
            
            // 准备审批数据
            const approvalData = {
              disbursementId: currentLoan.value.disbursementId,
              decision: approvalForm.decision === 'approve' ? '1' : '2', // 1:通过, 2:拒绝
              comment: approvalForm.comment,
              approvedAmount: approvalForm.decision === 'approve' ? approvalForm.approvedAmount : undefined
            }
            
            await lendingApi.submitApproval(approvalData)
            
            ElMessage.success('审批提交成功')
            approvalDialogVisible.value = false
            getPendingApprovalList() // 刷新列表
          } catch (error) {
            console.error('审批提交失败', error)
            ElMessage.error('审批提交失败：' + (error.message || '未知错误'))
          } finally {
            loading.value = false
          }
        }
      })
    }

    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
      getPendingApprovalList()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      currentPage.value = 1
      getPendingApprovalList()
    }

    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      getPendingApprovalList()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      getPendingApprovalList()
    }

    // 对话框关闭处理
    const handleDialogClose = () => {
      approvalDialogVisible.value = false
    }

    // 格式化金额
    const formatAmount = (amount) => {
      if (!amount && amount !== 0) return '--'
      return Number(amount).toLocaleString('zh-CN', {
        style: 'currency',
        currency: 'CNY',
        minimumFractionDigits: 2
      })
    }

    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        'pending': 'warning',
        'processing': 'primary',
        'approved': 'success',
        'rejected': 'danger'
      }
      return statusMap[status] || 'info'
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'pending': '待审批',
        'processing': '审批中',
        'approved': '已通过',
        'rejected': '已拒绝'
      }
      return statusMap[status] || '未知状态'
    }

    // 获取审批结果类型
    const getApprovalType = (decision) => {
      return decision === '1' ? 'success' : 'danger'
    }

    // 获取审批结果文本
    const getApprovalText = (decision) => {
      return decision === '1' ? '通过' : '拒绝'
    }

    onMounted(() => {
      getPendingApprovalList()
    })

    return {
      searchForm,
      loading,
      approvalList,
      total,
      currentPage,
      pageSize,
      approvalDialogVisible,
      currentLoan,
      detailDialogVisible,
      approvalHistoryList,
      approvalFormRef,
      approvalForm,
      approvalRules,
      getPendingApprovalList,
      viewDetail,
      handleApproval,
      submitApproval,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleDialogClose,
      formatAmount,
      getStatusType,
      getStatusText,
      getApprovalType,
      getApprovalText
    }
  }
}
</script>

<style scoped>
.loan-approval {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

:deep(.el-descriptions) {
  margin-bottom: 20px;
}

:deep(.el-timeline) {
  margin-top: 20px;
  padding: 20px;
}
</style> 